<template>
    <view style="padding: 15px;">
        <u-form ref="validateFormRef" :model="validateForm.value" :label-width="150">
            <u-form-item label="省市区" prop="region" required>
                <u-input type="select" :select-open="pickerShow" v-model="validateForm.value.region" placeholder="省市区县、乡镇等" @click="pickerShow = true"/>
            </u-form-item>
            <u-form-item label="商城名称" prop="communityName" required>
                <u-input type="select" v-model="validateForm.value.communityName" placeholder="请选择商城" @click="selectCommunity()"/>
            </u-form-item>
            <u-form-item label="登录账号" prop="username" required>
                <u-input v-model="validateForm.value.username" placeholder="请输入登录账号"/>
            </u-form-item>
            <u-form-item label="登录密码" prop="password" required>
                <u-input type="password" v-model="validateForm.value.password" placeholder="请输入登录密码"/>
            </u-form-item>
            <u-form-item label="确认密码" prop="confirmPassword" required>
                <u-input type="password" v-model="validateForm.value.confirmPassword" placeholder="请输入确认密码"/>
            </u-form-item>
            <u-form-item label="邮箱" prop="email" required>
                <u-input v-model="validateForm.value.email" placeholder="请输入邮箱"/>
            </u-form-item>
            <u-form-item label="验证码" prop="identifyingCode" required>
                <u-input placeholder="请输入验证码" v-model="validateForm.value.identifyingCode" type="text"></u-input>
                <u-button slot="right" type="success" size="mini" @click="getCode">{{codeTips}}</u-button>
            </u-form-item>
        </u-form>

        <view class="agreement">
            <u-checkbox size="40" shape="circle" active-color="red" v-model="isAgreement"></u-checkbox>
            <view class="agreement-text" @click="navigateTo(`/pages/common/agreement/index`)">
                <label style="text-decoration: underline;">勾选代表同意uview商城模板的版权协议</label>
            </view>
        </view>

        <u-button type="error" @click="submit" :disabled="!isAgreement">提交</u-button>
        <!--选择省市区-->
        <u-picker mode="region" v-model="pickerShow" @confirm="regionConfirm" v-if="!validateForm.value.provinceName"></u-picker>
        <u-picker mode="region" v-model="pickerShow" @confirm="regionConfirm" v-if="validateForm.value.provinceName"
                  :default-region="[validateForm.value.provinceName, validateForm.value.cityName, validateForm.value.areaName]"></u-picker>
        <!--邮箱验证码-->
        <u-verification-code seconds="60" ref="uCode" @change="codeChange"></u-verification-code>
    </view>
</template>

<script>

    import {CommonService} from "../../../../../dev/services/common.service";
    import {CommonUtil} from "../../../../../dev/core/utils/common.util";
    import {SysUserService} from "../../../../../dev/services/sys-user.service";
    import {TbEmailIdentifyingCodeService} from "../../../../../dev/services/tb_email_identifying_code.service";
    import {UFormUtil} from "../../../../../dev/core/utils/u-form.util";

    export default {
        data() {
            return {
                pickerShow: false,
                isAgreement: false,
                codeTips: '',  // 获取验证码提示语
                validateForm: {
                    value: {
                        region: '',
                        provinceName: '',
                        cityName: '',
                        areaName: '',
                        communityId: '',
                        communityName: '',
                        username: '',
                        password: '',
                        confirmPassword: '',
                        email: '',
                        identifyingCode: ''
                    },
                    rules: {
                        region: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                        ],
                        communityName: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                        ],
                        username: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    new CommonService().uniqueCheckByFields({
                                        'tableName': 'sys_user',
                                        'fieldList': [
                                            {'fieldName': 'username', 'fieldValue': value}
                                        ],
                                        'excludeId': null
                                    }).then(result => {
                                        if (result.status === "fail") {
                                            callback(new Error('登录账号已存在！'));
                                        } else {
                                            callback();
                                        }
                                    });
                                }
                            }
                        ],
                        password: [
                            {required: true, message: '请输入登录密码!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '请输入登录密码!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    if (this.validateForm.value.confirmPassword) {
                                        UFormUtil.validation(this.$refs.validateFormRef, 'confirmPassword');
                                    }
                                    callback();
                                }
                            }
                        ],
                        confirmPassword: [
                            {required: true, message: '请输入确认密码!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '请输入确认密码!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    if (value !== this.validateForm.value.password) {
                                        callback(new Error('两次输入密码不一致！'))
                                    } else {
                                        callback();
                                    }
                                }
                            }
                        ],
                        email: [
                            {required: true, type: "email", message: '请输入有效的邮箱号码', trigger: ['change', 'blur']},
                        ],
                        identifyingCode: [
                            {required: true, message: '请输入邮箱验证码', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    new TbEmailIdentifyingCodeService().mailIdentifyingCodeCheck(this.validateForm.value.email, this.validateForm.value.identifyingCode).then(result => {
                                        if (result.status === "success") {
                                            callback()
                                        } else {
                                            callback(new Error(result.message));
                                        }
                                    });
                                }
                            }
                        ]
                    }
                }
            }
        },
        onReady() {
            const _self = this

        },
        methods: {
            // 选择地区回调
            regionConfirm(e) {
                console.log(e);
                this.validateForm.value.region = e.province.label + '-' + e.city.label + '-' + e.area.label;
                this.validateForm.value.provinceName = e.province.label;
                this.validateForm.value.cityName = e.city.label;
                this.validateForm.value.areaName = e.area.label;
                this.$forceUpdate();
            },
            selectCommunity() {
                if (!this.validateForm.value.region) {
                    CommonUtil.toast("请先选择省市区");
                    return;
                }
                this.navigateTo(`/pages/main/login/register/register-new-user/register-community-select/index`, null, this.validateForm.value);
            },
            codeChange(text) {
                this.codeTips = text;
            },
            // 获取验证码
            getCode() {
                const _self = this;
                if (this.$refs.uCode.canGetCode) {
                    // 模拟向后端请求验证码
                    uni.showLoading({
                        title: '正在获取验证码',
                        mask: true
                    });

                    this.validateForm.value.email = CommonUtil.trim(this.validateForm.value.email);
                    if (!this.validateForm.value.email) {
                        this.$u.toast('请先输入邮箱');
                        return;
                    }

                    new TbEmailIdentifyingCodeService().sendMailIdentifyingCode(this.validateForm.value.email).then(result => {
                        CommonUtil.alert(result.message);
                        uni.hideLoading();
                        // 通知验证码组件内部开始倒计时
                        _self.$refs.uCode.start();
                    });
                } else {
                    this.$u.toast('倒计时结束后再发送');
                }
            },
            submit() {
                const _self = this;
                this.$refs.validateFormRef.validate(valid => {
                    if (valid) {
                        console.log('验证通过', _self.validateForm.value);
                        CommonUtil.alert({
                            title: '提示！',
                            content: '确认提交吗？',
                            showCancel: true, // 是否显示取消按钮
                            success: function (res) {
                                if (res.cancel) { // 点击取消,默认隐藏弹框
                                } else { // 点击确定
                                    // 注册用户
                                    new SysUserService().register(_self.validateForm.value).then(registerResult => {
                                        if (registerResult.status === "success") {
                                            CommonUtil.alertReLaunch('注册成功！', "/pages/main/login/index");
                                        } else {
                                            CommonUtil.alert(registerResult.message);
                                        }
                                    });
                                }
                            }
                        });
                    } else {
                        console.log('验证失败');
                    }
                });
            }
        }
    }
</script>

<style lang="scss" scoped>
    @import "./index.scss";
</style>
